#!/usr/bin/env bash

# Name of the lvm volume group to use/create for iscsi volumes
VOLUME_GROUP=${VOLUME_GROUP:-nova-volumes}
VOLUME_NAME_PREFIX=${VOLUME_NAME_PREFIX:-volume-}
INSTANCE_NAME_PREFIX=${INSTANCE_NAME_PREFIX:-instance-}

if ! sudo vgs $VOLUME_GROUP; then
	DEV=${DEV:-/dev/xvdb}
	# Only create if the loopback device doesn't contain $VOLUME_GROUP
	if ! sudo vgs $VOLUME_GROUP; then sudo vgcreate $VOLUME_GROUP $DEV; fi
fi

sudo apt-get install tgt
sudo stop tgt || true
sudo start tgt

if sudo vgs $VOLUME_GROUP; then
	# Remove nova iscsi targets
	sudo tgtadm --op show --mode target | grep $VOLUME_NAME_PREFIX | grep Target | cut -f3 -d ' ' | sudo xargs -n1 tgt-admin --delete || true
	# Clean out existing volumes
	for lv in `sudo lvs --noheadings -o lv_name $VOLUME_GROUP`; do
	    # VOLUME_NAME_PREFIX prefixes the LVs we want
	    if [[ "${lv#$VOLUME_NAME_PREFIX}" != "$lv" ]]; then
	        sudo lvremove -f $VOLUME_GROUP/$lv
	    fi
	done
fi